package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.example.mapper.*;
import org.example.pojo.*;
import org.example.pojo.select.*;
import org.example.pojo.statis.StaffTrend;
import org.example.service.DApartmentService;
import org.example.service.DAssetService;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.stereotype.Service;


import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author chenhongkai
* @description 针对表【d_apartment】的数据库操作Service实现
* @createDate 2024-03-06 16:58:19
*/
@Service
public class DApartmentServiceImpl extends ServiceImpl<DApartmentMapper, DApartment>
    implements DApartmentService{
    @Autowired
    private DApartmentMapper dApartmentMapper;

    @Autowired
    private DStaffMapper dStaffMapper;

    @Autowired
    private DApartmentTypeMapper dApartmentTypeMapper;

    @Autowired
    private DAssetMapper dAssetMapper;

    @Autowired
    private DAmountMapper dAmountMapper;

    @Autowired
    private DRepairMapper dRepairMapper;
    public Result<Map> SelectAllApartmentStaffs(DApartmentSelect dApartmentSelect){

        Map apartmentMap = new HashMap();
        apartmentMap.put("currentPage",dApartmentSelect.getCurrentPage());
        apartmentMap.put("pageSize",dApartmentSelect.getPageSize());

        //按入住人员指定查询
        String staffId = dApartmentSelect.getStaffId();
        String staffName = dApartmentSelect.getStaffName();
        String staffAddress = dApartmentSelect.getStaffAddress();
        String staffGroup = dApartmentSelect.getStaffGroup();
        Integer staffAge = dApartmentSelect.getStaffAge();
        String staffSex = dApartmentSelect.getStaffSex();

        //是否按人员条件查询
        if( (staffName != null && !staffName.isEmpty()) ||
            (staffAddress != null && !staffAddress.isEmpty()) ||
            (staffGroup != null && !staffGroup.isEmpty()) ||
            (staffAge != null) ||
            (staffId != null && !staffId.isEmpty()) ||
            (staffSex != null && !staffSex.isEmpty())
        ){

            //筛查人员查询结果
            List<DApartment> dApartmentStaffList = new ArrayList<>();
            //按人员条件查询
            List<DStaff> selectDStaffs = dStaffMapper.selectStaffByOther(dApartmentSelect);

            List<DApartment> toAdd = new ArrayList<>();

            //清除原数据
//            dApartmentList.clear();

            for(DStaff selectDStaff : selectDStaffs){
            //获取搜索人员所在的宿舍
                LambdaQueryWrapper<DApartment> apartmentSelectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                apartmentSelectLambdaQueryWrapper.eq(DApartment::getApartmentId,selectDStaff.getApartmentId());
                DApartment selectDapartment = dApartmentMapper.selectOne(apartmentSelectLambdaQueryWrapper);

                //检查是否已经查出该宿舍
                boolean exist = false;
                for(DApartment dApartment : dApartmentStaffList){
                    if(Objects.equals(dApartment.getApartmentId(), selectDapartment.getApartmentId()))
                        exist = true;
                }

                //查询出的数据加入到结果(没有重复宿舍 且 没有相同性别)
                if(!exist){
//                    //人员所在宿舍的舍友
//                    List<DStaff> dStaffList = dStaffMapper.selectStaffByApartmentId(selectDapartment.getApartmentId());
//                    selectDapartment.setDStaffs(dStaffList);
//
//                    //检查是否查询员工性别
//                    if(!dApartmentSelect.getStaffSex().isEmpty()){
//                        //检查宿舍里是否存在其他性别人员
//                        for(DStaff dStaff : dStaffList){
//                            if(!Objects.equals(dStaff.getStaffSex(), dApartmentSelect.getStaffSex())){
//                                dApartmentStaffList.add(selectDapartment);
//                                break;
//                            }
//                        }
//                    }else{
//                        dApartmentStaffList.add(selectDapartment);
//                    }
                    dApartmentStaffList.add(selectDapartment);
                }

            }
            //按宿舍条件查询全部
            List<DApartment> apartments = dApartmentMapper.selectAllApartments_2(dApartmentSelect);

            dApartmentStaffList = dApartmentStaffList.stream()
                    .filter(da -> apartments.stream().anyMatch(das -> das.getApartmentId().equals(da.getApartmentId())))
                    .collect(Collectors.toList());

            // 计算起始索引（注意：数组索引从0开始）
            int startIndex = (dApartmentSelect.getCurrentPage() - 1) * dApartmentSelect.getPageSize();
            // 计算结束索引（注意：包含起始索引，不包含结束索引）
            int endIndex = startIndex + dApartmentSelect.getPageSize();

            // 确保不会超出数组边界
            if (endIndex > dApartmentStaffList.size()) {
                endIndex = dApartmentStaffList.size();
            }

            List<DApartment> dApartmentStaffListResult = new ArrayList<>();
            for (int i = startIndex; i < endIndex; i++) {
                dApartmentStaffListResult.add(dApartmentStaffList.get(i));
            }

            apartmentMap.put("apartmentData",dApartmentStaffListResult);
            apartmentMap.put("pageTotal",dApartmentStaffList.size());

        }
        //不按人员搜索
            else{
                //分页查询
                Page<DApartment> page = new Page<>(dApartmentSelect.getCurrentPage(),dApartmentSelect.getPageSize());
                IPage<DApartment> mapIPage = dApartmentMapper.selectAllApartments(page, dApartmentSelect);

                //分页查询结果
                List<DApartment> dApartmentList = mapIPage.getRecords();

                if(dApartmentSelect.getIsSelectStaff() != null && dApartmentSelect.getIsSelectStaff() == 0){
                    for(DApartment dApartment : dApartmentList){
                        //查询宿舍人员
                        List<DStaff> dStaffList = dStaffMapper.selectStaffByApartmentId(dApartment.getApartmentId());
                        dApartment.setDStaffs(dStaffList);

                        //查询宿舍资产
                        LambdaQueryWrapper<DAsset> assetLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        assetLambdaQueryWrapper.eq(DAsset::getApartmentId,dApartment.getApartmentId());
                        List<DAsset> dAssets = dAssetMapper.selectList(assetLambdaQueryWrapper);
                        dApartment.setDAssets(dAssets);
                    }
                }

                apartmentMap.put("apartmentData",dApartmentList);
                apartmentMap.put("pageTotal",mapIPage.getTotal());
            }

        return Result.ok(apartmentMap);
    }

    @Override
    public Result<DApartment> SelectOneApartmentStaffs(DApartmentSelect dApartmentSelect) {
        //搜索指定宿舍信息
        LambdaQueryWrapper<DApartment> apartmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLambdaQueryWrapper.eq(DApartment::getApartmentId,dApartmentSelect.getApartmentId());
        DApartment selectDapartment = dApartmentMapper.selectOne(apartmentLambdaQueryWrapper);

        //宿舍中的入住人员
        List<DStaff> dStaffList = dStaffMapper.selectStaffByApartmentId(dApartmentSelect.getApartmentId());

        //该宿舍的总资产
        Double assets = dAssetMapper.SelectSumAssetByApartmentId(dApartmentSelect.getApartmentId());

        //该宿舍的水电热水费用
        DAmountSelect dAmountSelect = new DAmountSelect();
        dAmountSelect.setApartmentId(dApartmentSelect.getApartmentId());

        // 定义一个DateTimeFormatter，用于将YearMonth格式化为YYYY-MM
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        // 使用formatter将currentYearMonth格式化为字符串
        String formattedDate = YearMonth.now().minusMonths(1).format(formatter);;
        dAmountSelect.setAmountDate(formattedDate);//默认查询上个月的水电费用
        List<DAmountSelect> dAmountSelects = dAmountMapper.SelectAmountByApartmentId(dAmountSelect);

        selectDapartment.setDStaffs(dStaffList);
        selectDapartment.setAssets(assets);
        if(!dAmountSelects.isEmpty()){
            double amountSum = 0;
            for(DAmountSelect dAmountSelectResult : dAmountSelects){
                amountSum += dAmountSelectResult.getAmount();
            }
            selectDapartment.setAmount(Math.round(amountSum * 100.0) / 100.0);
        }
        return Result.ok(selectDapartment);
    }

    @Override
    public Result<DApartment> updateApartment(DApartment dApartment) {

        LambdaQueryWrapper<DStaff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DStaff::getApartmentId,dApartment.getApartmentId());
        List<DStaff> dStaffList = dStaffMapper.selectList(lambdaQueryWrapper);
//        if(dStaffList.size() > dApartment.getNumberOfPeople()){
//            return Result.warning(501,"入住人数比房间类型可容纳人数多");
//        }

        //计算出宿舍剩余床位
//        dApartment.setVacancy(dApartment.getNumberOfPeople()-dStaffList.size());

        //更新时间
        dApartment.setUpdateDate(new Date());
        System.out.println("dApartment = " + dApartment);
        int i = dApartmentMapper.updateById(dApartment);
        if(i == 0){
            return Result.error("更新失败");
        }
        return Result.ok(null);
    }

    @Override
    public Result<Map> SelectApartmentTypeApi(DApartment dApartment) {
        LambdaQueryWrapper<DApartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(dApartment.getApartmentType() != null && !dApartment.getApartmentType().isEmpty()){
            lambdaQueryWrapper.eq(DApartment::getApartmentType,dApartment.getApartmentType());
        }
        List<DApartment> apartmentList = dApartmentMapper.selectList(lambdaQueryWrapper);

        Map<String, List<DApartment>> DApartmentsMap = apartmentList.stream()
                .collect(Collectors.groupingBy(DApartment::getBuildingId));

        return Result.ok(DApartmentsMap);
    }

    @Override
    public Result<Integer> SelectVacancyByApartmentId(DApartment dApartment) {
        LambdaQueryWrapper<DApartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DApartment::getApartmentId,dApartment.getApartmentId());
        DApartment selectApartment = dApartmentMapper.selectOne(lambdaQueryWrapper);
        return Result.ok(selectApartment.getVacancy());
    }

    @Override
    public Result<Map> AddApartments(DApartmentSelect dApartmentSelect) {
        for(DApartment dApartment: dApartmentSelect.getApartments()){
            LambdaQueryWrapper<DApartment> dApartmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dApartmentLambdaQueryWrapper.eq(DApartment::getApartmentId,dApartment.getApartmentId());
            DApartment selectDApartment = dApartmentMapper.selectOne(dApartmentLambdaQueryWrapper);
            if(selectDApartment != null)
                return Result.warning(501,"宿舍房间号"+dApartment.getApartmentId()+"已经存在");
            dApartment.setVacancy(dApartment.getNumberOfPeople());
            dApartmentMapper.insert(dApartment);
        }
        return Result.ok(null);
    }

    @Override
    public Result<Map> DeleteApartment(DApartment dApartment) {
        int row = dApartmentMapper.deleteById(dApartment);
        if (row == 0) return Result.error("删除宿舍房间失败");
        return Result.ok(null);
    }

    @Override
    public Result<Map> StaticApartment() {

        //查询宿舍总数
        Long apartmentAllNumber = dApartmentMapper.selectCount(null);
        //查询满人宿舍数量
        LambdaQueryWrapper<DApartment> lambdaQueryWrapperFullApartment = new LambdaQueryWrapper<>();
        lambdaQueryWrapperFullApartment.nested(wrapper -> wrapper
                .eq(DApartment::getVacancy, 0)
                .or() // 注意这里的or()是LambdaQueryWrapper的内置方法，用于连接wrapper内的条件
                .eq(DApartment::getApartmentStatus, 0)
        );
        Long apartmentFullNumber= dApartmentMapper.selectCount(lambdaQueryWrapperFullApartment);
        //查询空宿舍数量
        Long apartmentEmptyNumber= dApartmentMapper.selectEmptyApartment();
        //查询未满人宿舍数量
        Long apartmentNotFullNumber= apartmentAllNumber-(apartmentFullNumber+apartmentEmptyNumber);

        //宿舍类型数据
        List<Map> apartmentTypes = dApartmentMapper.selectApartmentTypes();

        //宿舍总资产统计数据
        Double assetAllPrice = dAssetMapper.selectAllPrice();

        //宿舍总水电费用数据
        Double amountAll = dAmountMapper.selectAllAmount();


        Map staticMap = new HashMap();
        staticMap.put("allApartment",apartmentAllNumber);
        staticMap.put("fullApartment",apartmentFullNumber);
        staticMap.put("notFullApartment",apartmentNotFullNumber);
        staticMap.put("emptyApartment",apartmentEmptyNumber);
        staticMap.put("apartmentTypes",apartmentTypes);
        staticMap.put("assetAllPrice",assetAllPrice);
        staticMap.put("amountAll",amountAll);

        PendingStaffSelect pendingStaffSelect = new PendingStaffSelect();
        ResignStaffSelect resignStaffSelect = new ResignStaffSelect();

        //查询总可容纳的人员数量
        Integer capacityDormitory = 0;
        LambdaQueryWrapper<DApartment> apartmentsCapacityLambdaQueryWrapper = new LambdaQueryWrapper();
        apartmentsCapacityLambdaQueryWrapper.ne(DApartment::getApartmentId,"W外宿")
                .ne(DApartment::getApartmentId,"W夫妻");
        List<DApartment> apartmentsCapacity = dApartmentMapper.selectList(apartmentsCapacityLambdaQueryWrapper);
        for(DApartment dApartment : apartmentsCapacity){
            capacityDormitory += dApartment.getNumberOfPeople();
        }
        //查询现在宿人员数量
        LambdaQueryWrapper<DStaff> dStaffAllLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dStaffAllLambdaQueryWrapper.eq(DStaff::getIsDeleted,1);
        Long staffAll = dStaffMapper.selectCount(dStaffAllLambdaQueryWrapper);

        //查询已入住人员人数
        LambdaQueryWrapper<DStaff> dStaffInLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dStaffInLambdaQueryWrapper.ne(DStaff::getApartmentId,"W外宿")
                .ne(DStaff::getApartmentId,"W夫妻")
                .eq(DStaff::getIsDeleted,1);
        Long staffIn = dStaffMapper.selectCount(dStaffInLambdaQueryWrapper);
        //查询外宿人员人数
        LambdaQueryWrapper<DStaff> dStaffOutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dStaffOutLambdaQueryWrapper.eq(DStaff::getApartmentId,"W外宿")
                .or().eq(DStaff::getApartmentId,"W夫妻")
                .eq(DStaff::getIsDeleted,1);
        Long staffOut = dStaffMapper.selectCount(dStaffOutLambdaQueryWrapper);
        //查询待入住人员人数
        Integer staffPending = dStaffMapper.SelectPendingStaffsTotal(pendingStaffSelect);
        //查询离职人员人数
        Integer staffResign = dStaffMapper.SelectResignStaffTotal(resignStaffSelect);
        //查询异常人员人数
        ExceptionStaffSelect exceptionStaffSelect = new ExceptionStaffSelect();
        Integer staffException = dStaffMapper.SelectExceptionStaffTotal(exceptionStaffSelect);

        staticMap.put("capacityDormitory",capacityDormitory);
        staticMap.put("nowCapacityDormitory",capacityDormitory-staffAll);
        staticMap.put("staffAll",staffAll);
        staticMap.put("staffIn",staffIn);
        staticMap.put("staffOut",staffOut);
        staticMap.put("staffPending",staffPending);
        staticMap.put("staffResign",staffResign);
        staticMap.put("staffException",staffException);

        return Result.ok(staticMap);
    }

    @Override
    public Result<Map> SyncVacancy() {

        List<DApartment> dApartmentList = dApartmentMapper.selectList(null);
        for(DApartment dApartment : dApartmentList){
            LambdaQueryWrapper<DStaff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DStaff::getApartmentId,dApartment.getApartmentId());
            lambdaQueryWrapper.eq(DStaff::getIsDeleted,"1");
            List<DStaff> dStaffList = dStaffMapper.selectList(lambdaQueryWrapper);

            //计算出宿舍剩余床位
            dApartment.setVacancy(dApartment.getNumberOfPeople()-dStaffList.size());

            //更新时间
            dApartment.setUpdateDate(new Date());
            System.out.println(dApartment.getApartmentId());
            System.out.println(dApartment.getVacancy());
            dApartmentMapper.updateById(dApartment);

        }
        return Result.ok(null);
    }

    @Override
    public Result<List<DApartmentType> > SelectApartmentType() {
        List<DApartmentType> dApartmentTypes = dApartmentTypeMapper.selectList(null);
        return Result.ok(dApartmentTypes);
    }

    @Override
    public Result<List<DAsset>> SelectAssetByApartmentId(DAsset dAsset) {

        List<DAsset> dAssets= dAssetMapper.SelectAssetByApartmentId(dAsset.getApartmentId());
        return Result.ok(dAssets);
    }

    @Override
    public Result<List<DAsset>> AddAsset(List<DAsset> dAssets) {
        for(DAsset dAsset : dAssets){
            dAssetMapper.insert(dAsset);
        }
        return Result.ok(null);
    }

    @Override
    public Result<List<DAsset>> DeleteAsset(List<DAsset> dAssets) {
        for(DAsset dAsset : dAssets){
            dAssetMapper.deleteById(dAsset);
        }
        return Result.ok(null);
    }

    @Override
    public Result<List<DAsset>> UpdateAsset(List<DAsset> dAssets) {
        for(DAsset dAsset : dAssets){
            dAsset.setUpdateDate(new Date());
            dAssetMapper.updateById(dAsset);
        }
        return Result.ok(null);
    }

    @Override
    public Result<List<DApartment>> SelectApartmentInfo() {
        List<DApartment> apartments = dApartmentMapper.selectApartmentInfo();
        return Result.ok(apartments);
    }

    @Override
    public Result<List<Map>> GetApartmentAnalyze(DApartment dApartment) {
        List<DApartment> apartments = dApartmentMapper.selectAllAndAll(dApartment);

        List<Map> resultMap = new ArrayList<>();
        for (DApartment department : apartments) {

            String id = department.getApartmentId();
            Integer vacancy = department.getVacancy();
            Integer peopleNumber = department.getNumberOfPeople();
            Integer apartmentStatus = department.getApartmentStatus();
            String apartmentType = department.getApartmentType();

            if (id.length() == 4 && Character.isLetter(id.charAt(0)) && Character.isDigit(id.charAt(1)) &&
                    Character.isDigit(id.charAt(2)) && Character.isDigit(id.charAt(3))) {
                List<Object> result = new ArrayList<>();
//                if(id.charAt(0) == 'A'){
                    result.add(Integer.parseInt(id.substring(2, 4))-1); // 第三、四个字符作为数组的第二个值
                    result.add(id.charAt(1)- '2'); // 第二个字符（索引为1）作为数组的第一个值
//                }else if(id.charAt(0) == 'B'){
//                    result.add(Integer.parseInt(id.substring(2, 4))-1+24); // 第三、四个字符作为数组的第二个值
//                    result.add(id.charAt(1)- '2'); // 第二个字符（索引为1）作为数组的第一个值
//                }else if(id.charAt(0) == 'C'){
//                    result.add(Integer.parseInt(id.substring(2, 4))-1+39); // 第三、四个字符作为数组的第二个值
//                    result.add(id.charAt(1)- '2'); // 第二个字符（索引为1）作为数组的第一个值
//                }

                // 判断值
                if(Objects.equals(vacancy, peopleNumber)  || peopleNumber == 0)
                    result.add(9);
                else
                    result.add(vacancy);

                List<Object> fList = new ArrayList<>();
                fList.add(result);

                Map map = new HashMap();
                map.put("name",id);
                map.put("data",fList);
                map.put("peopleNumber",peopleNumber);
                map.put("apartmentType",apartmentType);
                if(Objects.equals(vacancy, peopleNumber) || peopleNumber == 0){
                    map.put("apartmentStatus","空房间");
                }else if(vacancy == 0 || apartmentStatus == 0){
                    map.put("apartmentStatus","满人房");
                }else{
                    map.put("apartmentStatus","未满人");
                }

                resultMap.add(map);
//                transformedList.add(result);
            }
        }

        return Result.ok(resultMap);
    }


    @Override
    public Result<Map> GetApartmentTrend() {

        List<StaffTrend> staffTrends = new ArrayList<>();

        //2022年开始
        LocalDate currentDate =LocalDate.of(2022, 1, 1);
        LocalDate endDate = LocalDate.now();

        //循环遍历，每一周
        while (!currentDate.isAfter(endDate)) {
            LocalDate firstDayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate lastDayOfWeek = firstDayOfWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

            StaffTrend staffTrend = new StaffTrend();
            //每一周的周数、起始时间、结束时间
//            staffTrend.setYearWeek(String.format("%04d%02d", firstDayOfWeek.getYear(), firstDayOfWeek.get(ChronoField.ALIGNED_WEEK_OF_YEAR)));
            staffTrend.setYearWeek(String.format("%02d", firstDayOfWeek.get(ChronoField.ALIGNED_WEEK_OF_YEAR)));
            staffTrend.setFirstDayOfWeek(firstDayOfWeek.toString());
            staffTrend.setLastDayOfWeek(lastDayOfWeek.toString());

            //每周入住人数、离宿人数、在住人数
            Integer weekCheckIns = dStaffMapper.getWeekCheckIn(firstDayOfWeek.toString(),lastDayOfWeek.toString());
            Integer weekCheckOuts = dStaffMapper.getWeekCheckOut(firstDayOfWeek.toString(),lastDayOfWeek.toString());
            Integer NowCheckIns = dStaffMapper.getWeekStaffNumber(lastDayOfWeek.toString());

            staffTrend.setWeekCheckIns(weekCheckIns);
            staffTrend.setWeekCheckOuts(weekCheckOuts);
            staffTrend.setNowCheckIns(NowCheckIns);

            staffTrends.add(staffTrend);

            // 移动到下一周的第一天
            currentDate = lastDayOfWeek.plusDays(1);

        }


        Map result = new HashMap();
        result.put("staffTrends",staffTrends);

        return Result.ok(result);
    }

    @Override
    public Result<Map> GetVacancyTotal(DApartment dApartment) {
        //剩余床位数
        Long vacancyTotal = dApartmentMapper.getVacancyTotal(dApartment);

        System.out.println(vacancyTotal);
        Map vacancyTotalMap = new HashMap();
        vacancyTotalMap.put("vacancyTotal",vacancyTotal);

        return Result.ok(vacancyTotalMap);
    }

//    @Override
//    public Result<List<Map<String, Object>>> GetApartmentAnalyze(DApartment dApartment) {
//        List<DApartment> apartments = dApartmentMapper.selectAllAndAll(dApartment);
//        Map<String, List<Map<String, String>>> groupedApartments = new HashMap<>();
//
//        //总入住人数
//        Integer sumPeopleNumber = 0;
//        for (DApartment apt : apartments) {
//            String buildingName = apt.getBuildingId();
//            String apartmentName = apt.getApartmentId();
//            String apartmentType = apt.getApartmentType();
//            String staffNames = apt.getStaffNames();
//            Integer vacancy = apt.getVacancy();
//            Integer peopleNumber = apt.getNumberOfPeople();
//            Double assets = apt.getAssets();
//            sumPeopleNumber += peopleNumber;
//
//            // 检查是否已经有该楼栋的条目
//            groupedApartments.putIfAbsent(buildingName, new ArrayList<>());
//
//            // 创建一个新的房间对象
//            Map room = new HashMap<>();
//            room.put("name", apartmentName);
//            if(Objects.equals(buildingName, "W栋"))
//                room.put("value", 10); // 每个房间的值设为1
//            else
//                room.put("value", 1); // 每个房间的值设为1
//            room.put("vacancy", vacancy);
//            room.put("peopleNumber", peopleNumber);
//            room.put("apartmentType", apartmentType);
//            room.put("staffNames", staffNames);
//            room.put("assets", assets);
//
//            //配置房间状态颜色
//            Map<String, String> itemStyle = new HashMap<>();
//            if(vacancy == 0)
//                itemStyle.put("color", "#862121");
//            else if (vacancy.equals(peopleNumber))
//                itemStyle.put("color", "#939393");
//            else if (vacancy > 0 && vacancy < 4)
//                itemStyle.put("color", "#f39623");
//            else
//                itemStyle.put("color", "#019a18");
//
//            room.put("itemStyle", itemStyle);
//
//            groupedApartments.get(buildingName).add(room);
//        }
//
//        // 将Map转换为所需的格式（这里直接处理输出，而不是转换为另一个列表）
//        List<Map<String, Object>> result = new ArrayList<>();
//        for (Map.Entry<String, List<Map<String, String>>> entry : groupedApartments.entrySet()) {
//            Map<String, Object> building = new HashMap<>();
//            building.put("name", entry.getKey());
//            if(entry.getKey().equals("W栋"))
//                building.put("value", 20); // 这里是children的数量
//            else
//                building.put("value", entry.getValue().size()); // 这里是children的数量
//
//            building.put("children", entry.getValue());
//
//            //总的数据
//            int totalVacancy = 0;
//            int totalPeopleNumber = 0;
//            Double totalAsset = 0.0;
//            // 遍历当前建筑物的所有房间
//            for (Map room : entry.getValue()) {
//                // 假设每个房间都有一个"vacancy"字段
//                if (room.containsKey("vacancy")) {
//                    try {
//                        totalVacancy += (int) room.get("vacancy");
//                    } catch (NumberFormatException e) {
//                        // 如果转换失败，可以记录错误或忽略该值
//                        System.err.println("Invalid area value for room in building " + entry.getKey());
//                    }
//                }
//                if (room.containsKey("peopleNumber")) {
//                    try {
//                        totalPeopleNumber += (int) room.get("peopleNumber");
//                    } catch (NumberFormatException e) {
//                        // 如果转换失败，可以记录错误或忽略该值
//                        System.err.println("Invalid area value for room in building " + entry.getKey());
//                    }
//                }
//                if (room.containsKey("assets") && room.get("assets") != null) {
//                    try {
//                        totalAsset += (Double) room.get("assets");
//                    } catch (NumberFormatException e) {
//                        // 如果转换失败，可以记录错误或忽略该值
//                        System.err.println("Invalid area value for room in building " + entry.getKey());
//                    }
//                }
//            }
//
//            // 设置房间属性总和
//            building.put("vacancy", totalVacancy);
//            building.put("peopleNumber", totalPeopleNumber);
//            building.put("assets", totalAsset);
//
//            result.add(building);
//        }
//
//        return Result.ok(result);
//    }

}




